package com.southwind.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.southwind.common.ResultObj;
import com.southwind.common.SalesPageModel;
import com.southwind.entity.AfterSalesMessage;
import com.southwind.entity.Sales;
import com.southwind.entity.Station;
import com.southwind.service.SalesService;
import com.southwind.vo.AfterSalesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/sales")
public class SalesController {

    @Autowired
    private SalesService salesService;

    @GetMapping("/list")
    public Map list(SalesPageModel salesPageModel){
        Page<Sales> page = new Page<>(salesPageModel.getPage(), salesPageModel.getLimit());
        Page<Sales> resultPage;
        if(salesPageModel.getStatus()!=null){
            QueryWrapper<Sales> queryWrapper = new QueryWrapper<>();

            if(salesPageModel.getStatus().equals("生效中")){
                queryWrapper.ge("losedate", new Date());
            }
            if(salesPageModel.getStatus().equals("已过期")){
                queryWrapper.le("losedate", new Date());
            }
            resultPage = this.salesService.page(page, queryWrapper);
        } else {
            resultPage = this.salesService.page(page);
        }
        for (Sales record : resultPage.getRecords()) {
            if(new Date().after(record.getLosedate())){
                record.setStatus("已过期");
            } else {
                record.setStatus("生效中");
            }
        }
        Map map = new HashMap();
        map.put("count", resultPage.getTotal());
        map.put("data", resultPage.getRecords());
        return map;
    }

    @PostMapping("/add")
    public ResultObj add(@RequestBody Sales sales){
        boolean save = this.salesService.save(sales);
        if(save) return ResultObj.SALES_ADD_SUCCESS;
        return ResultObj.SALES_ADD_ERROR;
    }

    @PostMapping("/update")
    public ResultObj update(@RequestBody Sales sales){
        boolean updateById = this.salesService.updateById(sales);
        if(updateById) return ResultObj.SALES_UPDATE_SUCCESS;
        return ResultObj.SALES_UPDATE_ERROR;
    }

    @DeleteMapping("/delete/{id}")
    public ResultObj delete(@PathVariable("id") Integer id){
        boolean removeById = this.salesService.removeById(id);
        if(removeById) return ResultObj.SALES_DELETE_SUCCESS;
        return ResultObj.SALES_DELETE_ERROR;
    }
}

